package com.anne.fish.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.anne.fish.service.ArticleCatManager;
import com.anne.fish.model.ArticleCat;
import com.anne.fish.webapp.action.BaseAction;

import java.util.List;

public class ArticleCatAction extends BaseAction implements Preparable {
    private ArticleCatManager articleCatManager;
    private List articleCats;
    private ArticleCat articleCat;
    private Long id;
    private String query;

    public void setArticleCatManager(ArticleCatManager articleCatManager) {
        this.articleCatManager = articleCatManager;
    }

    public List getArticleCats() {
        return articleCats;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String articleCatId = getRequest().getParameter("articleCat.id");
            if (articleCatId != null && !articleCatId.equals("")) {
                articleCat = articleCatManager.get(new Long(articleCatId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        articleCats = articleCatManager.search(query, ArticleCat.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public ArticleCat getArticleCat() {
        return articleCat;
    }

    public void setArticleCat(ArticleCat articleCat) {
        this.articleCat = articleCat;
    }

    public String delete() {
        articleCatManager.remove(articleCat.getId());
        saveMessage(getText("articleCat.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            articleCat = articleCatManager.get(id);
        } else {
            articleCat = new ArticleCat();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (articleCat.getId() == null);

        articleCatManager.save(articleCat);

        String key = (isNew) ? "articleCat.added" : "articleCat.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}